package com.mst;

import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/student2")
public class Student2Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 给前端返回一个json数组
        // 1. 设置响应的格式
        resp.setContentType("application/json;charset=utf-8");
        // 2. 组织json的字符串
        // [{"name":"李四"},{"name":"张三"}]
        // ["天亮","尚云"]
//        String jsonArr = "[\"天亮\",\"尚云\"]";
//        String jsonArr = " [{\"name\":\"李四\"},{\"name\":\"张三\"}]";
        // 使用fastjson构建json字符串
//        JSONArray jsonArray = new JSONArray();
//        Student student = new Student("张三", 18);
//        jsonArray.add(student);
//        jsonArray.add(new Student("李四",99));
//        jsonArray.add(new Student("王五", 97));

//        1. 通过jdbc连接到数据，查询到student表的完整数据（）

//        JSONArray == 数组
//        JSONObject == HashMap
        List<Student> students = new ArrayList<Student>();
        students.add(new Student("李四", 99));
        students.add(new Student("王五", 97));

        // 3. 把json字符串写给客户端
//        resp.getWriter().write(jsonArr);
//        resp.getWriter().write(jsonArray.toJSONString());
        resp.getWriter().write(JSONObject.toJSONString(students));
    }
}
